package com.mio.web.controller.sys;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.durcframework.core.DefaultGridResult;
import org.durcframework.core.GridResult;
import org.durcframework.core.MessageResult;
import org.durcframework.core.controller.CrudController;
import org.durcframework.core.expression.ExpressionQuery;
import org.durcframework.core.expression.subexpression.ListExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.mio.web.common.MioUtil;
import com.mio.web.entity.sys.SysUpload;
import com.mio.web.entity.sys.SysUploadSch;
import com.mio.web.service.product.ProductService;
import com.mio.web.service.sys.SysUploadService;


@Controller
public class SysUploadController extends CrudController<SysUpload, SysUploadService> {
	
	@Autowired
	private SysUploadService sysUploadService;
	
	
	
	
	// 鏂板璁板綍
	@RequestMapping("/addSysUpload.do")
	public @ResponseBody Map<String, Object> addSysUpload(SysUpload entity,HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/"+entity.getFuncId()+"/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				//遍历
				while (iter.hasNext()) {
					System.out.println(iter.hasNext());
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (!myFileName.trim().equals("")) {
							System.out.println(myFileName);
							// 定义上传路径
							File targetFile = MioUtil.getUploadFile(request, entity.getFuncId(), myFileName,response);
							file.transferTo(targetFile);
							
							SysUpload sysUpload = new SysUpload();
							sysUpload.setFileSize((int)file.getSize());
							sysUpload.setFileFullPath(relPath+myFileName);
							sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
							sysUpload.setFuncId(entity.getFuncId());
							sysUpload.setZipId(entity.getZipId());
							sysUpload.setSortId(entity.getSortId());
							sysUpload = sysUploadService.save(sysUpload);
						}
					}
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		resultMap.put("success", true);
		resultMap.put("info", entity);

		return resultMap;
	}

	// 鍒犻櫎璁板綍
	@RequestMapping("/delSysUpload.do")
	public @ResponseBody MessageResult delSysUpload(SysUpload entity) {
		return this.delete(entity);
	}

	// 淇敼璁板綍
	@RequestMapping("/updateSysUpload.do")
	public @ResponseBody MessageResult updateSysUpload(SysUpload entity,HttpServletRequest request,HttpServletResponse response) 
			throws IllegalStateException, IOException  {
		SysUpload old = this.getService().get(entity.getId());
		int change1 = Integer.parseInt(request.getParameter("change1"));
		boolean flag = false;
		//表示修改
		if(change1>0){
			flag = true;
		}
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/"+old.getFuncId()+"/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				String picId = "";
				int count = 0;
				// 产品图
				String productImg = "";
				while (iter.hasNext()) {					
					if(flag){
						System.out.println("  "+iter.hasNext());
						// 记录上传过程起始时的时间，用来计算上传时间
						int pre = (int) System.currentTimeMillis();
						// 取得上传文件
						MultipartFile file = multiRequest.getFile(iter.next());
						if (file != null) {
							// 取得当前上传文件的文件名称
							String fileName = file.getOriginalFilename();
							// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
							if (!fileName.trim().equals("")) {
								System.out.println(fileName);
								// 定义上传路径
								File targetFile = MioUtil.getUploadFile(request, old.getFuncId(), fileName,response);
								file.transferTo(targetFile);
								old.setFileSize((int) file.getSize());
								old.setFileFullPath(relPath + fileName);
								old.setCreatedTime(entity.getCreatedTime());
								old.setSortId(entity.getSortId());
								old.setZipId(entity.getZipId());
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		return this.update(old);
	}

	// 鏉′欢鏌ヨ鍒嗛〉鎿嶄綔
	@RequestMapping("/listSysUpload.do")
	public @ResponseBody GridResult listSysUpload(SysUploadSch searchEntitySch) {
		return this.query(searchEntitySch);
	}

	@RequestMapping("/findSysUploadByIds.do")
	public @ResponseBody Object findSysUploadByIds(SysUpload entity, HttpServletRequest request) {
		ExpressionQuery query = new ExpressionQuery();
		String[] ids = request.getParameter("ids").split(",");
		query.add(new ListExpression("id", Arrays.asList(ids)));
		DefaultGridResult resultGrid = (DefaultGridResult) this.query(query);
		@SuppressWarnings("unchecked")
		List<SysUpload> rows = (List<SysUpload>) resultGrid.getRows();
		return rows;
	}

	// 鏉′欢鏌ヨ骞惰繑鍥炴墍鏈夎褰�
	@RequestMapping("/listAllSysUpload.do")
	public @ResponseBody Object listAllSysUpload(SysUploadSch searchEntitySch) {
		DefaultGridResult result = (DefaultGridResult) this.queryAll(searchEntitySch);
		List<SysUpload> list = (List<SysUpload>) result.getRows();
		SysUpload sysUpload = new SysUpload();
		sysUpload.setId(0);
		sysUpload.setClientName("空");
		list.add(sysUpload);
		return new DefaultGridResult(list);
	}

	// 鑾峰彇璇︾粏淇℃伅
	@RequestMapping("/getSysUploadById.do")
	public @ResponseBody SysUpload getSysUploadById(SysUpload entity) {
		return this.getService().get(entity.getId());
	}
	
	//根据picId获取图片路径
	@RequestMapping("/loadPics.do")
	public @ResponseBody Object loadPics(String picId){
		String[] picIds = picId.split(",");
		String urls = "";
		for(int i= 0;i<picIds.length; i++){
			SysUpload pic = this.getService().get(Integer.parseInt(picIds[i]));
			if(pic != null){
				String fileFullPath = pic.getFileFullPath();
				urls += fileFullPath.substring(fileFullPath.lastIndexOf("/")+1)+",";
			}
		}
		urls = urls.substring(0,urls.length()-1);
		return urls;
	}

}